<template>
  <div id="app">
    <!-- 路由出口 + 表格内容（与商品页面结构对齐） -->
    
    <!-- 添加按钮 -->
    <el-button type="primary" @click="openAddDialog">添加用户</el-button>
    
    <!-- 用户表格（保持与商品表格相同的布局风格） -->
    <el-table :data="userList" style="width: 100%" border stripe>
      <el-table-column prop="id" label="用户ID" width="120" />
      <el-table-column prop="name" label="用户姓名" width="150" />
      <el-table-column prop="password" label="用户密码" width="180" />
      <el-table-column prop="phone" label="手机号码" width="180" />
      <el-table-column prop="address" label="用户地址" />
      
      <!-- 操作列（保持与商品页面完全一致） -->
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑用户弹窗（与商品弹窗结构对齐） -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef"
        label-width="80px" 
        style="padding: 20px;"
      >
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="formData.id" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入用户密码" type="password" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="用户地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入用户地址" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'UserManagement',
  data() {
    return {
      userList: [], // 用户列表数据
      dialogVisible: false, // 弹窗显示状态
      dialogTitle: '添加用户', // 弹窗标题（区分添加/编辑）
      formData: { // 表单数据
        id: '',
        name: '',
        password: '',
        phone: '',
        address: ''
      },
      formRef: null, // 表单引用
      rules: { // 表单验证规则
        id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        name: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
        ],
        address: [{ required: false, message: '请输入用户地址', trigger: 'blur' }]
      },
      currentId: null // 当前操作的用户ID（区分添加/编辑）
    }
  },
  mounted() {
    this.getUserList(); // 页面加载时获取用户列表
  },
  methods: {
    // 获取用户列表（与后端UserController的selectAll接口对应）
    async getUserList() {
      try {
        const res = await axios.get('http://127.0.0.1:8080/users');
        this.userList = res.data.map(item => ({
          id: item.id,
          name: item.name,
          password: item.password,
          phone: item.phone,
          address: item.address
        }));
      } catch (err) {
        ElMessage.error('获取用户列表失败');
        console.error(err);
      }
    },
    
    // 打开添加用户弹窗
    openAddDialog() {
      this.currentId = null;
      this.dialogTitle = '添加用户';
      this.formData = {
        id: '',
        name: '',
        password: '',
        phone: '',
        address: ''
      };
      this.$refs.formRef?.resetFields();
      this.dialogVisible = true;
    },
    
    // 打开编辑用户弹窗
    openEditDialog(row) {
      this.currentId = row.id;
      this.dialogTitle = '编辑用户';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    
    // 提交表单（添加/编辑用户）
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        
        try {
          if (this.currentId) {
            await axios.put(`http://127.0.0.1:8080/users/${this.currentId}`, this.formData);
            ElMessage.success('修改用户成功');
          } else {
            await axios.post('http://127.0.0.1:8080/users', this.formData);
            ElMessage.success('添加用户成功');
          }
          
          this.dialogVisible = false;
          this.getUserList();
        } catch (err) {
          ElMessage.error(this.currentId ? '修改用户失败' : '添加用户失败');
          console.error(err);
        }
      });
    },
    
    // 删除用户
    async deleteUser(id) {
      try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await axios.delete(`http://127.0.0.1:8080/users/${id}`);
        ElMessage.success('删除用户成功');
        this.getUserList();
      } catch (err) {
        if (err.name !== 'cancel') {
          ElMessage.error('删除用户失败');
          console.error(err);
        }
      }
    }
  }
}
</script>

<style scoped>
/* 完全复用商品页面的样式，确保布局一致 */
.content {
  padding-top: 60px;
}

/* 操作按钮间距（与商品页面保持一致） */
.el-table .el-button {
  margin-right: 5px;
}


</style>